package com.yc.fav.service.impl;

import com.yc.fav.entity.FavFavorite;
import com.yc.fav.entity.FavTag;
import com.yc.fav.entity.FavTagFavorite;
import com.yc.fav.mapper.FavFavoriteMapper;
import com.yc.fav.mapper.FavTagFavoriteMapper;
import com.yc.fav.mapper.FavTagMapper;
import com.yc.fav.service.BizException;
import com.yc.fav.service.IFavFavoriteService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yc.fav.util.MybatisHelper;
import org.apache.ibatis.session.SqlSession;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 云收藏-收藏表-6 服务实现类
 * </p>
 *
 * @author wz
 * @since 2022-11-06
 */
@Service
public class FavFavoriteServiceImpl extends ServiceImpl<FavFavoriteMapper, FavFavorite> implements IFavFavoriteService {
public void add(FavFavorite ff) throws BizException {
    //数据验证
    if(ff.getFlabel() == null || ff.getFlabel().trim().isEmpty()){
        throw  new BizException("填写网站名称");
    }
    if(ff.getFurl() == null || ff.getFurl().trim().isEmpty()){
        throw  new BizException("填写网站地址");
    }
    SqlSession session  = MybatisHelper.getSession();
    FavFavoriteMapper favoriteMapper =session.getMapper(FavFavoriteMapper.class);
    FavTagMapper tagMapper = session.getMapper(FavTagMapper.class);
    FavTagFavoriteMapper tagFavoriteMapper = session.getMapper(FavTagFavoriteMapper.class);
    //用户输入正确写入链表
    favoriteMapper.insert(ff);
    //
    //
    //
    //
    //
    String ftags = ff.getFtags();
    String[] tags = ftags.split("[,;，；]+");
    for (String tag:tags
         ) {
        //tagMapper.update(实体对象，条件)
        if(tagMapper.updateTcount(tag) == 0){
            //如果没有修改到数据库这条记录那么要新增
            FavTag ft= new FavTag();
            ft.setTname(tag);
            ft.setTcount(1);
            tagMapper.insert(ft);
            //新增tag之后 在关系表中添加记录
            FavTagFavorite ftf = new FavTagFavorite();
            //mybatis-plus会返回新增的id值
            ftf.setTid(ft.getId());//tag的id
            ftf.setFid(ff.getId());
            tagFavoriteMapper.insert(ftf);
        }else{

        }

    }
}
}
